package simulator;

import java.util.ArrayList;

/**
 * The FileSystem class provides an encapsulation for the set of FileObjects,
 * and keeps track of the number of disk reads/writes for our simulation.
 * @author Paul
 *
 */
public class FileSystem {

	
	ArrayList<FileObject> files;
	int numWrites;
	int numReads;
	
	public SystemSim ss;
	public JournalArea ja;
	public BufferCache bc;
	
	public void setsystem(SystemSim ss, JournalArea ja, BufferCache bc)
	{
		this.ss = ss;
		this.ja = ja;
		this.bc = bc;
	}

	
	/**
	 * The file system constructor takes as input an arraylist of file objects
	 */
	public FileSystem(ArrayList<FileObject> newFiles){
		numWrites = 0;
		numReads = 0;
		files = newFiles;
	}
	
	/**
	 * Add the file to the file system. Should not really be used, so I may delete it.
	 * @param f: the file to be added
	 */
	public void AddFile(FileObject f)
	{
		for(int i = 0; i < files.size(); i++) //Make sure there doesn't already exist file with same name
		{
			FileObject currentFile = files.get(i);
			if(f.getName().equals(currentFile.getName()))
			{
				System.out.println("\nUnable to add file: a file already exists with the sane name\n");
				return;
			}
		}
		files.add(f);
	}
	
	
	/**
	 * Return the file with the specified name
	 * @param fileName
	 * @return the desired file object
	 */
	public FileObject getFile(String fileName){
		
		for(int i = 0; i < files.size(); i++)
		{
			FileObject currentFile = files.get(i);
			if(currentFile.getName().equals(fileName))
			{
				numReads++;
				return currentFile; //file was found successfully
			}
		}
		
		System.out.println("\nError: the file does not exist.");
		return null;
	}
	
	/**
	 * Update the file with the given file name
	 * @param fileName
	 * @param value
	 */
	public void updateFile(String fileName, int value){
		
		for(int i = 0; i < files.size(); i++) //iterate through to find the desired file
		{
			FileObject currentFile = files.get(i);
			if(currentFile.getName().equals(fileName))
			{
				numWrites++; //update the number of file writes
				currentFile.setData(value);
				return;
			}
		}
		
		System.out.println("\nError: the file does not exist.");
	}
	
	public int getWrites()
	{
		return numWrites;
	}
	
	public int getReads()
	{
		return numReads;
	}
	
	public String SimString(){
		String str;
		str = "Number of files written to file system: " + numWrites + "\nNumber of files read from file system: " + numReads;
		return str;
	}

}
